package com.jyet.jdbtool.main;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.SpringLayout;
/**
 * 主窗口
 * @author jyet
 *
 */
public class MainFrame {
	static JFrame frame;

	public static void main(String[] args) {
		frame = new JFrame();
		initFrame(frame);
		frame.setJMenuBar(buildJMenuBar());
		frame.setLayout(buildLayout());
		frame.addKeyListener(buildKeyListener());
		buildSystemTray();
	}
	
	/**
	 * 使用托盘，在windows下会出现乱码须指定字符集 -Dfile.encoding=GB18030 
	 */
	private static void buildSystemTray() {
		SystemTray st = SystemTray.getSystemTray();
		try {
			Image image = new BufferedImage(32, 32, BufferedImage.TYPE_3BYTE_BGR);
			TrayIcon ti = new TrayIcon(image);
			PopupMenu pm = new PopupMenu();
			MenuItem quit = new MenuItem("退出");
			quit.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					System.exit(0);
				}
			});
			pm.add(quit);
			ti.setPopupMenu(pm);
			st.add(ti);
			ti.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent e) {
					frame.setVisible(true);
				}
			});
		} catch (AWTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static KeyListener buildKeyListener() {
		KeyAdapter ka = new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
					frame.setVisible(false);
				}
			}
		};
		return ka;
	}

	private static void initFrame(JFrame frame) {
		// 读取配置
		// frame.setBounds(r);
		frame.setAlwaysOnTop(true);
		frame.setVisible(true);
		frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
		frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
	}

	private static JMenuBar buildJMenuBar() {
		JMenuBar jmb = new JMenuBar();
		JMenu menu = new JMenu();
		menu.setText("文件");
		jmb.add(menu);
		
		return jmb;
	}

	private static SpringLayout buildLayout() {
		SpringLayout layout = new SpringLayout();
		return layout;
	}
}
